package com.maysham.tripod.dao;

import com.maysham.tripod.config.Constants;
import com.maysham.tripod.model.Log;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;

@Repository
public class LogDao {
    @Resource
    private MongoTemplate template;

    public Log save(Log log){
        return template.save(log);
    }

    public void writeLog(Log log, String line) {
        String lineWithTime = new SimpleDateFormat(Constants.LOG_TIME_FORMAT_PATTERN).format(new Date()) + line;
        template.updateFirst(Query.query(Criteria.where("id").is(log.getId())), new Update().push("lines", lineWithTime), Log.class);
    }
}
